//
//  RoomInfoViewController.swift
//  HinsLive
//
//  Created by haoxian on 2019/5/2.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import SVProgressHUD


class RoomInfoViewController: ViewController {
    
    let categories: [FeedsCategory.CategoryItem]
    
    let infoView: RoomInfoView
    
    var submitClosure: ((RoomInfo) -> Void)?
    var cancelClosure: (() -> Void)?
    
    init(category: FeedsCategory) {
        self.categories = category.categories
        self.infoView = RoomInfoView(titles: self.categories.map{ $0.title })
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupInfoView()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        UIView.animate(withDuration: 0.3) {
            self.view.backgroundColor = UIColor(white: 0.1, alpha: 0.5)
            self.infoView.transform = CGAffineTransform.identity
        }
    }
}

private extension RoomInfoViewController {
    func setupInfoView() {
        view.addSubview(infoView)
        infoView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(40)
            make.right.equalToSuperview().offset(-40)
            make.height.equalTo(281)
            make.centerY.equalToSuperview()
        }
        
        infoView.transform = CGAffineTransform(scaleX: 0, y: 0)
        
        infoView.cancelBtn.rx.tap.subscribe(onNext: { [weak self] _ in
            self?.dismiss()
        })
        .disposed(by: bag)
        
        infoView.submitBtn.rx.tap
            .subscribe(onNext: { [weak self] _ in
                self?.submitDidTap()
            })
            .disposed(by: bag)
        
        infoView.roomTitleTF.rx.text.orEmpty
            .map { return $0.count > 0}
            .bind(to: infoView.submitBtn.rx.isEnableTap)
            .disposed(by: bag)
    }
    
    func dismiss() {
        UIView.animate(withDuration: 0.3, animations: {
            self.view.backgroundColor = UIColor(white: 0.1, alpha: 0)
            self.infoView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
        }, completion: { isFinish in
            guard isFinish else { return }
            self.cancelClosure?()
        })
    }
    
    func submitDidTap() {
        guard let submit = submitClosure, let title = infoView.roomTitleTF.text, infoView.roomTypeTitleView.selectedIndex <= categories.count else { fatalError() }
        let typeItem = categories[infoView.roomTypeTitleView.selectedIndex]
        let user = AccountManager.share.user
        let roomInfo = RoomInfo(ruid: user.uid, roomTitle: title, fid: typeItem.fid, name: user.name, avatarURL: user.avatarURL)
        submit(roomInfo)
    }
}
